package databases

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/prometheus"
)

// 常量定义
const (
	MySQLDefaultCharset = "utf8mb4"
	MySQLDefaultPort    = 3306
	PrometheusHTTPPort  = 9991
	PrometheusRefresh   = 15
)

// MySQLConfig MySQL 数据库配置
type MySQLConfig Database

// 确保实现了InitDBter接口
var _ InitDBter = (*MySQLConfig)(nil)

// InitDB 初始化MySQL数据库连接
func (d *MySQLConfig) InitDB() *gorm.DB {
	// 设置默认值
	d.setMySQLDefaults()

	// 构建DSN连接字符串
	dsn := d.buildDSN()

	// 创建数据库连接
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(fmt.Sprintf("MySQL数据库连接失败: %v", err))
	}

	// 配置监控指标
	if d.Metrics {
		d.setupPrometheus(db)
	}

	return db
}

// setMySQLDefaults 设置MySQL默认配置
func (d *MySQLConfig) setMySQLDefaults() {
	if d.Charset == "" {
		d.Charset = MySQLDefaultCharset
	}
	if d.Port == 0 {
		d.Port = MySQLDefaultPort
	}
}

// buildDSN 构建MySQL DSN连接字符串
func (d *MySQLConfig) buildDSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		d.Username, d.Password, d.Host, d.Port, d.Database, d.Charset)
}

// setupPrometheus 配置Prometheus监控
func (d *MySQLConfig) setupPrometheus(db *gorm.DB) {
	err := db.Use(prometheus.New(prometheus.Config{
		DBName:          d.Name,
		RefreshInterval: PrometheusRefresh,
		StartServer:     true,
		HTTPServerPort:  PrometheusHTTPPort,
		MetricsCollector: []prometheus.MetricsCollector{
			&prometheus.MySQL{
				VariableNames: []string{"Threads_running"},
			},
		},
	}))
	if err != nil {
		panic(fmt.Sprintf("配置Prometheus监控失败: %v", err))
	}
}

func (d *MySQLConfig) TRUNCATETable(db *gorm.DB, tableName string) error {
	return db.Exec(fmt.Sprintf("TRUNCATE TABLE %s", tableName)).Error
}
